import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hbtrans_flutter/apis.dart';
import 'package:hbtrans_flutter/beans/traintype_bean.dart';
import 'package:hbtrans_flutter/const.dart';
import 'package:hbtrans_flutter/enroll/traintypepage.dart';
import 'package:hbtrans_flutter/event/TrainTypeEvent.dart';
import 'package:hbtrans_flutter/utils/fluro.dart';
import 'package:hbtrans_flutter/utils/mydio.dart';
import 'package:hbtrans_flutter/view/loading.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';

import '../routes.dart';

class Sign extends StatefulWidget {
  final phone;
  final address;
  final name;
  final inscode;

  const Sign({Key key, this.phone, this.address, this.name, this.inscode})
      : super(key: key);

  @override
  _SignState createState() => _SignState();
}

class _SignState extends State<Sign> with SingleTickerProviderStateMixin {
  ScrollController _scrollViewController;
  TabController _tabController;
  LoadingDialog loadingDialog;
  var inscode = '';
  var userId = '';
  var classId = '';
  var schname = '';
  var lists = List();
  Map<String, dynamic> data = Map();


  @override
  void initState() {
    super.initState();
    _scrollViewController = ScrollController(initialScrollOffset: 0.0);
    _tabController = TabController(vsync: this, length: 3);
    setState(() {
      inscode = widget.inscode;
    });
    eventBus.on<TrainTypeEvent>().listen((TrainTypeEvent data)=> _updateView(data));
    getUserInfo();
  }
  void getUserInfo() async{
    SharedPreferences sp=await SharedPreferences.getInstance();
    userId=sp.getString("id");
  }

  _updateView(TrainTypeEvent data) {
    setState(() {
      classId=data.id;
      schname=data.name;
    });
    print(classId+'======'+schname);
  }

  @override
  void dispose() {
    super.dispose();
    _scrollViewController.dispose();
    _tabController.dispose();
    MyDio.getInstance().clearInstance();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        title: Text(
          "驾校信息",
          style: TextStyle(color: Colors.white, fontSize: 17),
        ),
        backgroundColor: Color(0xff23AFDC),
        centerTitle: true,
      ),
      body: Theme(
        data: ThemeData(primaryColor: Colors.white),
        child: Column(
          children: <Widget>[
            Expanded(
                flex: 10,
                child: NestedScrollView(
                  controller: _scrollViewController,
                  headerSliverBuilder:
                      (BuildContext context, bool innerBoxIsScrolled) {
                    return <Widget>[
                      SliverAppBar(
                        automaticallyImplyLeading: false,
                        pinned: true,
                        floating: true,
                        expandedHeight: 260,
                        flexibleSpace: FlexibleSpaceBar(
                          collapseMode: CollapseMode.pin,
                          background: Container(
                            height: double.infinity,
                            color: Colors.white,
                            child: Column(
                              children: <Widget>[
                                Stack(
                                  children: <Widget>[
                                    SizedBox(
                                      height: 165,
                                      child: Image.asset(
                                        'images/ic_sign_bg.png',
                                        fit: BoxFit.fill,
                                      ),
                                    ),
                                    Padding(
                                      padding:
                                          EdgeInsets.fromLTRB(10, 130, 10, 9),
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: <Widget>[
                                          Text(
                                            FluroConvertUtils
                                                .fluroCnParamsDecode(
                                                    widget.name),
                                            style: TextStyle(
                                                color: Colors.white,
                                                fontSize: 14),
                                          ),
                                          SizedBox(
                                            width: 10,
                                          ),
                                          Text(
                                            '1120人',
                                            style: TextStyle(
                                                color: Colors.white,
                                                fontSize: 12),
                                          ),
                                        ],
                                      ),
                                    )
                                  ],
                                ),
                                Padding(
                                  padding: EdgeInsets.fromLTRB(15, 9, 15, 10),
                                  child: Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: <Widget>[
                                      Row(
                                        children: <Widget>[
                                          Image.asset(
                                            'images/icon_loction.png',
                                            height: 22,
                                            width: 16,
                                            fit: BoxFit.fill,
                                          ),
                                          SizedBox(
                                            width: 10,
                                          ),
                                          Text(
                                            FluroConvertUtils
                                                .fluroCnParamsDecode(
                                                    widget.address),
                                            style: TextStyle(
                                                color: Colors.black,
                                                fontSize: 12),
                                          ),
                                        ],
                                      ),
                                      GestureDetector(
                                        onTap: () {
                                          _launchPhone(widget.phone);
                                        },
                                        child: Image.asset(
                                          'images/icon_sign_phone.png',
                                          height: 22,
                                          width: 18,
                                          fit: BoxFit.fill,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                Container(
                                  height: 3,
                                  color: Colors.grey[100],
                                )
                              ],
                            ),
                          ),
                        ),
                        bottom: TabBar(controller: _tabController, tabs: [
                          Tab(text: "班型"),
                          Tab(text: "训练场"),
                          Tab(text: "教练"),
                        ]),
                      ),
                    ];
                  },
                  body: TabBarView(controller: _tabController, children: [
                    TrainTypePage(inscode),
                    Page(),
                    Page(),
                  ]),
                )),
            Expanded(
              flex: 1,
              child: _button(),
            )
          ],
        ),
      ),
    );
  }

  _info() {
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          SizedBox(
            height: 44,
            child: Text(
              '驾校信息',
              style: TextStyle(color: Colors.black, fontSize: 14),
            ),
          ),
          Padding(
            padding: EdgeInsets.fromLTRB(10, 13, 10, 13),
            child: Text(
              ' 这是一条关于驾校详细信息的简单介绍，包括场地面积的大小，教练人数以及驾校可以教授的车型简介等，不超过200字为最佳。',
              style: TextStyle(color: Colors.black, fontSize: 14),
            ),
          ),
        ],
      ),
    );
  }

  _button() {
    return MaterialButton(
      height: 42,
      minWidth: MediaQuery.of(context).size.width,
      onPressed: () {
        _signup();
      },
      child: Text(
        "报名学车",
        style: TextStyle(color: Colors.white, fontSize: 16),
      ),
      color: Color(0xff23AFDC),
    );
  }

  _showDialog() {
    loadingDialog = LoadingDialog(
      text: '请稍候...',
    );
    showDialog<Null>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return loadingDialog;
        });
  }

  // 学员报名
  _signup() async {
//    _showDialog();
    Map<String,dynamic> data = Map();
    data['inscode'] = widget.inscode;
    data['userId'] = userId;
//    data['classId'] = 'ac7724e8b2126ccab7617e8f70ec0f16';
    data['classId'] = classId;
//    data['schname'] = '涿州明城恒盛集团驾驶员培训有限公司';
    data['schname'] = widget.name;
    MyDio.getInstance(url: Const.TRANS_SERVER_PATH_NEW3).post(Apis.signUp, (data) {
      print(data);

      if (loadingDialog != null) {
        loadingDialog = null;
        Navigator.pop(context);
      }
//        _saveOrderId(data);
      String route = '${Routes.pay}?orderId=${data}';
        Routes.router.navigateTo(context, route,
            replace: false, transition: TransitionType.fadeIn);
    },params: data);
  }

  _saveOrderId(String data) async{
    SharedPreferences sharedPreferences=await SharedPreferences.getInstance();
    sharedPreferences.setString("orderId", data);
  }


  _launchPhone(phone) async {
    String url = 'tel:' + phone;
    launch(url);
  }


}


class Page extends StatefulWidget {
  //fragment
  const Page({Key key}) : super(key: key);

  @override
  _PageState createState() => _PageState();
}

class _PageState extends State<Page> {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(18, 1, 18, 0),
      child: _doWidgets(),
    );
  }

  _doWidgets() {
    return Center(
      child: Column(
        children: <Widget>[
          Image.asset(
            'images/ic_school_null.png',
            fit: BoxFit.fill,
          ),
          SizedBox(
            height: 15,
          ),
          Text(
            '暂未开通',
            style: TextStyle(color: Color(0xff999999), fontSize: 14),
          ),
        ],
      ),
    );
  }
}
